package org.mojo.plugin.tibco.designer;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * Start the businessworks Tibco designer and point to the .TIBCO/ preference folder of the 
 * 
 * parent project.
 * 
 * @author Corentin Lonfils
 * 
 * 
 * @goal businessworks
 */
public class TibcoDesignerRun extends AbstractMojo {

	
	private static final String TIBCO_ENV_PREF = "TIBCO_ENV_PREF";


	//TODO if unix or if windows
	private static final String DESIGNER_EXEC = "designer.exe";


	//default location looking for C:/tibco/designer/ 
	//TODO should be configurable in the plugin instead of hardcoded
	private String defaultDesignerPath = "/tibco/designer/5.6/bin/";


	/**
	 * @parameter expression="${project}"
	 * @required
	 * @readonly
	 */
	private MavenProject project;

	static String[] mapToStringArray(Map<String, String> map) {
        final String[] strings = new String[map.size()];
        int i = 0;
        for (Map.Entry<String, String> e : map.entrySet()) {
            strings[i] = e.getKey() + '=' + e.getValue();
            i++;
        }
        return strings;
    }
	
	/**
	 * Set a TIBCO_ENV_PREF with the project Base directory and start the designer
	 * 
	 * 
	 * @throws Exception
	 */
    public void cmd() throws Exception {
        final Map<String, String> env = new HashMap<String, String>(System.getenv());
        env.put(TIBCO_ENV_PREF, project.getBasedir().getAbsolutePath());
        final String[] strings= mapToStringArray(env);
        Runtime.getRuntime().exec(defaultDesignerPath+DESIGNER_EXEC, strings, new File(defaultDesignerPath));
    }

    
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (!project.getPackaging().equals("pom")){
			return;
		}
		try {
			cmd();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
